package com.efounder.chat.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.adapter.NeiKongSelectImageAdapter;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.http.NeikongUploadImgRequest;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.chat.model.ShareCloudFile;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.common.BaseRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity;
import com.efounder.util.AppContext;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.CommonDecimalFormat;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.NetworkUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AfterPermissionGranted;
import sun.misc.BASE64Encoder;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.pansoft.chat.photo.JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE;

/**
 * 内控影像上传
 * Created by kongmeng on 2018/9/4.
 */

public class NeiKongUploadImageActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "NeiKongUploadImageActivity";

    private TextView tvTitle;
    private TextView tvSend;
    private TextView tvBillNumber;
    private TextView tvTotalPoints;
    //扣分
    private TextView tvPoints;
    private GridView gridView;
    private NeiKongSelectImageAdapter adapter;
    JSONObject jsonObject;
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪

    private ArrayList<ShareCloudFile> mPictureList = new ArrayList<>();//和选图联动的图片list
    private ArrayList<String> imgUrlList = new ArrayList<>();//图片的url list

    //每张图扣除1000积分
    private static final int AMOUNT = 1000;
    private static final int MAX_PIC = 20;
    //pc不在线 每张加50   pc在线 加 100
    private static int ITEM_AMOUNT = 50;
    //pc 是否在线
    boolean pcIsOnline = false;
    int totPoints;
    int points;
    //是否正在发送中
    private boolean isSending;

    //网络类型
    private NetworkUtils.NetworkType networkType;

    public static void start(Context context, String json) {
        Intent starter = new Intent(context, NeiKongUploadImageActivity.class);
        //a代表的是单据编号，b代表的是单据类型，c代表的是制单人（工号）
        starter.putExtra("json", json);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uploadimage);

        try {
            jsonObject = new JSONObject(getIntent().getExtras().getString("json"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        initView();
        initData();
    }

    public void initData() {
        pictureAndCropManager = new PictureAndCropManager(this);
        tvSend.setText(R.string.common_text_upload);
        tvTitle.setText(getResources().getString(R.string.NeiKongUploadImageActivity_title));
        tvTotalPoints.setText(formatPoints(totPoints));

        try {
            tvBillNumber.setText(getResources().getString(R.string.NeiKongUploadImageActivity_billNumber, jsonObject.getString("a")));
            tvPoints.setText("+0");
            // tvPoints.setText("");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        getIntegral();
        isPCAccountOnline();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //获取积分
    private void getIntegral() {
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        NeikongUploadImgRequest.neikongCommonRequest(TAG, "integral/integralTotal", map,
                new NeikongUploadImgRequest.NeikongUploadImgRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.optString("result").equals("success")) {
                                totPoints = Integer.parseInt(jsonObject.optString("integralTotal"));
                                // if (totPoints > 20000) {
                                tvTotalPoints.setText(formatPoints(totPoints));

                                // }
// else {
//                            showAlert(getResources().getString(R.string.NeiKongUploadImageActivity_LackIntegral));
//                            LoadingDataUtilBlack.dismiss();
//                        }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
//                    showAlert(getResources().getString(R.string.NeiKongUploadImageActivity_IntegralRequestFaild));
//                    LoadingDataUtilBlack.dismiss();
                        }
                    }

                    @Override
                    public void onFail(String error) {
//                showAlert(getResources().getString(R.string.NeiKongUploadImageActivity_IntegralRequestFaild));
//                LoadingDataUtilBlack.dismiss();
                    }
                });

    }

    //更新积分
    private void updateReduceJiFen() {

        tvPoints.setText("+" + formatPoints(ITEM_AMOUNT * mPictureList.size()));
    }

    //判断pc是否在线
    public void isPCAccountOnline() {
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        params.put("passWord", EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD));
        JFCommonRequestManager.getInstance().requestGetByAsyn(TAG, String.format("%s/%s", EnvironmentVariable.getProperty("IMBaseUrl"),
                "IMServer/user/getSessionContextList"), params, new BaseRequestManager.ReqCodeCallBack<String>() {
            @Override
            public void onReqFailed(int errorCode, String errorMsg) {
                LoadingDataUtilBlack.dismiss();
                showAlert(getResources().getString(R.string.NeiKongUploadImageActivity_PCRequestFaild));
            }

            @Override
            public void onReqSuccess(String result) {
                LoadingDataUtilBlack.dismiss();
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optString("result").equals("success")) {
                            //返回成功
                            JSONArray deviceArray = jsonObject.optJSONArray("sessionContextList");
                            pcIsOnline = false;
                            if (deviceArray.length() > 0) {
                                for (int i = 0; i < deviceArray.length(); i++) {
                                    JSONObject deviceObj = deviceArray.optJSONObject(i);
                                    if ("pc".equals(deviceObj.optString("deviceClass"))) {
                                        pcIsOnline = true;
                                        ITEM_AMOUNT = 100;
                                    }
                                }
                            }
                            if (!pcIsOnline) {
                                ITEM_AMOUNT = 50;
                                showTip();
                                //showAlert(getResources().getString(R.string.NeiKongUploadImageActivity_PCIsOutline));
                            } else {
//                                tvSend.setEnabled(true);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        showAlert(getResources().getString(R.string.NeiKongUploadImageActivity_PCRequestFaild));
                    }
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {

            }
        });
    }

    private void showTip() {
        new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.common_text_hint))
                .setMessage(R.string.NeiKongUploadImageActivity_PCIsOutline1)
                .setPositiveButton(getResources().getString(R.string.common_text_continue), null)
                .setNegativeButton(getResources().getString(R.string.common_text_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                }).setCancelable(false)
                .create().show();
    }

    public void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvSend = (TextView) findViewById(R.id.tv_save);
        gridView = (GridView) findViewById(R.id.gridview);
        tvTotalPoints = (TextView) findViewById(R.id.tv_total_points);
        tvPoints = (TextView) findViewById(R.id.tv_points);
        tvBillNumber = (TextView) findViewById(R.id.tv_billnumber);

        tvSend.setVisibility(View.VISIBLE);
        tvSend.setOnClickListener(this);
//        tvSend.setEnabled(false);

        initGridListener();
        adapter = new NeiKongSelectImageAdapter(this, mPictureList);
        adapter.setOnImgRemovedListener(new NeiKongSelectImageAdapter.OnImgRemovedListener() {
            @Override
            public void onImgRemoved(int position) {
                if (isSending) {
                    ToastUtils.showShort(getResources().getString(R.string.NeiKongUploadImageActivity_uploading));
                    return;
                }
                mPictureList.remove(position);
                updateReduceJiFen();
                adapter.notifyDataSetChanged();
            }
        });
        gridView.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.tv_save) {
            networkType = NetworkUtils.getNetworkType();
            if (mPictureList.size() == 0) {
                //没有选择图片
                ToastUtil.showToast(AppContext.getInstance(), R.string.wechatview_please_add_pic);
                return;
            }
//            if (totPoints < 20000) {
//                //积分不足两万
//                ToastUtils.showShort(getResources().getString(R.string.NeiKongUploadImageActivity_LackIntegral));
//                return;
//            }
//            if (totPoints <mPictureList.size()*AMOUNT) {
//                //总积分小于要扣除的积分
//                ToastUtils.showShort(getResources().getString(R.string.wechatview_neikong_jifenbuzu));
//                return;
//            }
            switch (networkType) {//网络类型
                case NETWORK_WIFI:
                    this.uploadFile();
                    break;
                case NETWORK_2G:
                    showNetAlert(ResStringUtil.getString(R.string.wechatview_upload_network_2g));
                    break;
                case NETWORK_3G:
                    showNetAlert(ResStringUtil.getString(R.string.wechatview_upload_network_3g));
                    break;
                case NETWORK_4G:
                    showNetAlert(ResStringUtil.getString(R.string.wechatview_upload_network_4g));
                    break;
                case NETWORK_NO:
                    showNoNetAlert(ResStringUtil.getString(R.string.wechatview_upload_network_no));
                    break;
                case NETWORK_UNKNOWN:
                    showNetAlert(ResStringUtil.getString(R.string.wechatview_upload_network_unknown));
                    break;
            }
            ;
        }
    }

    private void initGridListener() {
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //加号，选择图片
                if (position == mPictureList.size()) {
                    if (mPictureList.size() >= MAX_PIC) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.wechatview_no_choose_more_pic);
                        return;
                    }

                    String[] items = {ResStringUtil.getString(R.string.common_text_take_picture), ResStringUtil.getString(R.string.common_text_photo_album)};
                    new AlertDialog.Builder(NeiKongUploadImageActivity.this)
                            .setTitle(R.string.wechatview_title_choose_pic)

                            .setItems(items, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (which == 0) {
                                        startTakePhoto();
                                    } else {
                                        Intent intent = new Intent(NeiKongUploadImageActivity.this, JFPicturePickPhotoWallActivity.class);
                                        ArrayList<String> tempList = new ArrayList<>();
                                        for (int i = 0; i < mPictureList.size(); i++) {
                                            tempList.add(mPictureList.get(i).getCloudFilePath());
                                        }
                                        intent.putExtra("mPictureList", tempList);
                                        intent.putExtra(JFPicturePickPhotoWallActivity.MAX_NUM, MAX_PIC);//可选择的最大照片数
                                        intent.putExtra(JFPicturePickPhotoWallActivity.SHOW_RAW_PIC, false);//不显示原图
                                        intent.putExtra("sendBtnName", getResources().getString(R.string.common_text_confirm));
                                        intent.putExtra(JFPicturePickPhotoWallActivity.SELECT_MODE, JFPicturePickPhotoWallActivity.MODE_PIC_ONLY);
                                        startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
                                        //overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
                                    }
                                }
                            }).create().show();


                }
            }
        });
    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_CAMERA)
    private void startTakePhoto() {
        if (EasyPermissionUtils.checkCameraPermission()) {
            pictureAndCropManager.takePicture();
        } else {
            EasyPermissionUtils.requestCameraPermission(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureAndCropManager.PHOTO_REQUEST_TAKEPHOTO) {
                String picPath = pictureAndCropManager.getPicturePath();
                ShareCloudFile cloudFile = new ShareCloudFile();
                cloudFile.setCloudFilePath(picPath);
                mPictureList.add(cloudFile);
            } else if (requestCode == REQUEST_PIC_SELECTE_CODE) {
                //图库选择照片

                ArrayList<ShareCloudFile> tempCloudFiles = new ArrayList<>();
                ArrayList<String> tempList = (ArrayList<String>) data.getExtras().get("mSelectedPics");
                if (tempList.size() > 0) {
                    mPictureList.clear();
                }
                if (tempList.size() > MAX_PIC) {
                    ToastUtil.showToast(AppContext.getInstance(), R.string.wechatview_no_choose_more_pic);
                    tempList = (ArrayList<String>) tempList.subList(0, 9);
                }
                for (int i = 0; i < tempList.size(); i++) {

                    ShareCloudFile cloudFile = new ShareCloudFile();
                    cloudFile.setCloudFilePath(tempList.get(i));
                    tempCloudFiles.add(cloudFile);
                }
                mPictureList.addAll(tempCloudFiles);
            }
            updateReduceJiFen();
            adapter.notifyDataSetChanged();
        }

    }

    /**
     * 格式化积分
     *
     * @param points
     * @return
     */
    public static String formatPoints(int points) {
        if (!"".equals(points)) {
            BigDecimal bd = new BigDecimal(points);
            CommonDecimalFormat df = new CommonDecimalFormat(",###,###");
//            System.out.println("钱=="+df.format(bd));
            return df.format(bd);
        }
        return "";
    }

    private void showAlert(String msg) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.common_text_hint))
                .setMessage(msg)
                .setPositiveButton(getResources().getString(R.string.common_text_confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                }).setCancelable(false)
                .create().show();
    }

    private void showNoNetAlert(String msg) {//无网络的提示
        new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.common_text_hint))
                .setMessage(msg)
                .setPositiveButton(getResources().getString(R.string.common_text_confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).setCancelable(false)
                .create().show();
    }

    private void showNetAlert(String msg) {
        new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.common_text_hint))
                .setMessage(msg)
                .setPositiveButton(getResources().getString(R.string.common_text_confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        uploadFile();
                    }
                })
                .setNegativeButton(getResources().getString(R.string.common_text_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).setCancelable(false)
                .create().show();
    }


    //上传文件
    private void uploadFile() {
        showLoading(R.string.common_text_uploading);
        //压缩图片
        Disposable disposable = Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {
                List<String> filePathList = new ArrayList<>();
                for (int i = 0; i < mPictureList.size(); i++) {
                    ImageUtil.saveNewImage(mPictureList.get(i).getCloudFilePath(), 1280, 1280);
                    String filePath = ImageUtil.chatpath + ImageUtil.getFileName(mPictureList.get(i).getCloudFilePath()) + ".pic";
                    filePathList.add(filePath);

                }
                emitter.onNext(filePathList);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<String>>() {
                    @Override
                    public void accept(List<String> strings) throws Exception {
                        updateToServer(strings);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    private void updateToServer(List<String> filePathList) {
//        {"data":[
//            {"F_BILL_ID":"1222222222","F_BILL_TYPE":"32323","F_ATT_TITLE":"323112.jpg","F_ATT_SIZE":"834888","F_ATT_TYPE":"1","image":"base64"},
//            {"F_BILL_ID":"1222222222","F_BILL_TYPE":"32323","F_ATT_TITLE":"32323.jpg","F_ATT_SIZE":"834888","F_ATT_TYPE":"1","image":"base64"}
//	]}
        net.sf.json.JSONObject fileObject = new net.sf.json.JSONObject();
        net.sf.json.JSONArray jsonArray = new net.sf.json.JSONArray();
        for (String path : filePathList) {
            net.sf.json.JSONObject itemObject = new net.sf.json.JSONObject();
            File file = new File(path);
            if (!file.exists()) {
                continue;
            }
            String tempPath = path.replace(".pic", "");
            String fileTitle = tempPath.substring(path.lastIndexOf("/") + 1, tempPath.length());

            itemObject.put("F_BILL_ID", jsonObject.optString("a"));
            itemObject.put("F_ATT_TITLE", fileTitle);
            itemObject.put("F_ATT_SIZE", file.length());
            itemObject.put("F_BILL_TYPE", jsonObject.optString("b"));
            itemObject.put("F_ATT_TYPE", "1");
            itemObject.put("image", fileToBase64(file));
            jsonArray.add(itemObject);

        }
        fileObject.put("data", jsonArray);

//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
//                fileObject.toString());

//        JFCommonRequestManager.getInstance(AppContext.getInstance())
//                //.requestPostByAsyncWithRequsetBody(TAG, "http://192.168.248.41:8081/ImageUpload/UploadImage",
//                .requestPostByAsyncWithRequsetBody(TAG, "http://ics3.pansoft.com/ImageUpload/UploadImage",
//                        requestBody, new JFCommonRequestManager.ReqCallBack<String>() {
//                            @Override
//                            public void onReqSuccess(String result) {
//                                dismissLoading();
//                                showAlert(ResStringUtil.getString(R.string.common_text_upload_success));
////                                totPoints = totPoints - (AMOUNT * mPictureList.size());
////                                tvTotalPoints.setText(formatPoints(totPoints));
//                            }
//
//                            @Override
//                            public void onReqFailed(String errorMsg) {
//                                dismissLoading();
//                                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_upload_fail_again);
//                            }
//                        });

        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        params.put("imageData", fileObject.toString());
        params.put("pcOnline", pcIsOnline ? "1" : "0");
        String requestUrl = EnvironmentVariable.getProperty("TalkChainUrl") + "/tcserver/pansoft/accessories";
        JFCommonRequestManager.getInstance()
                //.requestPostByAsyncWithRequsetBody(TAG, "http://192.168.248.41:8081/ImageUpload/UploadImage",
                .requestPostByAsyn(TAG, requestUrl, params, new JFCommonRequestManager.ReqCodeCallBack<String>() {
                    @Override
                    public void onReqFailed(int errorCode, String errorMsg) {
                        dismissLoading();
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_upload_fail_again);
                        //todo 针对区块链应用，如果errorcode =400 表示用户登录失效，需要重新登录 yqs
                        if (errorCode == 400 && EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
                                .getString(R.string.special_appid))) {
                            //发送弹框提示用户
                            EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE));
                        }
                    }

                    @Override
                    public void onReqSuccess(String result) {
                        try {
                            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                            if (jsonObject.optString("result", "").equals("success")) {
                                dismissLoading();
                                showAlert(ResStringUtil.getString(R.string.common_text_upload_success));
                            } else {
                                dismissLoading();
                                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_upload_fail_again);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            dismissLoading();
                            ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_upload_fail_again);
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {

                    }
                });
    }

    /**
     * 文件转base64字符
     *
     * @param file
     * @return
     */
    public String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {

            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            in.read(bytes);
            base64 = new BASE64Encoder().encode(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }


}
